import 'package:casdon/modules/me/data/api/service_channel_list_api.dart';
import 'package:casdon/modules/me/domain/usecase/service_channel_list_usecase.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class ServiceChannelListNotifier
    extends AutoDisposeAsyncNotifier<List<ServiceChannel>> {
  List<ServiceChannel> allData = [];

  @override
  Future<List<ServiceChannel>> build() async {
    // 不上来就获取数据，原因是数据量比较大，希望可以在再次进入页面时无需获取而使用缓存（延迟释放），等到彻底退出报装报修再释放
    return [];
  }

  Future<void> fetchData() async {
    if (allData.isEmpty == false) {
      state = AsyncData(allData);
      return;
    }
    if (state == AsyncValue.loading()) {
      return;
    }
    state = const AsyncValue.loading();

    final ret = await ref.read(serviceChannelListUsecaseProvider).execute();
    allData = ret?.entities ?? [];
    state = AsyncData(allData);
    return;
  }

  // ✅ 搜索功能
  void search(String keyword) {
    if (keyword.isEmpty == false) {
      List<ServiceChannel> filterData = allData
          .where(
            (channel) =>
                channel.name.toLowerCase().contains(keyword.toLowerCase()),
          )
          .toList();
      state = AsyncValue.data(filterData);
      return;
    }

    clearSearch();
  }

  // ✅ 清除搜索
  void clearSearch() {
    state = AsyncValue.data(allData);
  }
}

final serviceChannelListProvider =
    AsyncNotifierProvider.autoDispose<
      ServiceChannelListNotifier,
      List<ServiceChannel>
    >(ServiceChannelListNotifier.new);
